package kr.ac.kaist.ysproject;

import kr.ac.kaist.ysproject.data.DataProfile;
import kr.ac.kaist.ysproject.facebook.BaseRequestListener;
import kr.ac.kaist.ysproject.facebook.SessionEvents;
import kr.ac.kaist.ysproject.facebook.SessionEvents.AuthListener;
import kr.ac.kaist.ysproject.facebook.SessionStore;
import kr.ac.kaist.ysproject.option.ProfileOptionMenu;
import kr.ac.kaist.ysproject.util.Constant;
import kr.ac.kaist.ysproject.util.DbManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;



public class ProfileActivity extends Activity {
	
	DataProfile dataProfile = null;
	
	Activity act = this;
	TabHost tabHost;
	float totalRating = 0;
	
	private static final int SELECT_PICTURE = 1;
	String m_picturePath = "";
	
	// FACEBOOK 연동관련 변수
	public static final String APP_ID = "203459523071632";
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
        
        mFacebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);
        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        
        
        /***********************************************************************
		 * 
		 * 
		 * 탭 구조 정의
		 * 
		 * 
		 ***********************************************************************/
        
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        
        TabSpec spec1 = tabHost.newTabSpec("Tab1");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator(getString(R.string.tab1));
        spec1.setIndicator(getString(R.string.tab1), getResources().getDrawable(R.drawable.information));
        tabHost.addTab(spec1);
        
        TabSpec spec2 = tabHost.newTabSpec("Tab2");
        spec2.setContent(R.id.tab2);
        spec2.setIndicator(getString(R.string.tab2));
        spec2.setIndicator(getString(R.string.tab2), getResources().getDrawable(R.drawable.concern));
        tabHost.addTab(spec2);
        
        TabSpec spec3 = tabHost.newTabSpec("Tab3");
        spec3.setContent(R.id.tab3);
        spec3.setIndicator(getString(R.string.tab3));
        spec3.setIndicator(getString(R.string.tab3), getResources().getDrawable(R.drawable.star));
        tabHost.addTab(spec3);
        
        TabSpec spec4 = tabHost.newTabSpec("Tab4");
        spec4.setContent(R.id.tab4);
        spec4.setIndicator(getString(R.string.tab4));
        spec4.setIndicator(getString(R.string.tab4), getResources().getDrawable(R.drawable.facebook));
        tabHost.addTab(spec4);
        
        //
        // 탭 위젯 선택 시, 모든 항목들을 뷰모드로 전환
        //
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
		    	
				// 이름 항목 편집모드 닫기
		    	((EditText) findViewById(R.id.editTextName)).setVisibility(View.GONE);
				((TextView) findViewById(R.id.textViewName)).setText(((EditText) findViewById(R.id.editTextName)).getText());
				((TextView) findViewById(R.id.textViewName)).setVisibility(View.VISIBLE);
				
				// 기본정보 탭 항목들 편집모드 닫기
		    	for(int j=1; j<=Constant.PROFILE_DEFAULT_COUNT; j++) {
					int textViewId = getResources().getIdentifier("textViewDefault" + j, "id", getPackageName());
		    		if (textViewId <= 0) break;
		    		int EditTextId = getResources().getIdentifier("editTextDefault" + j, "id", getPackageName());
		    		if (EditTextId <= 0) break;
					((EditText) findViewById(EditTextId)).setVisibility(View.GONE);
					((TextView) findViewById(textViewId)).setText(((EditText) findViewById(EditTextId)).getText());
					((TextView) findViewById(textViewId)).setVisibility(View.VISIBLE);
				}
		    	
		    	// 관심사 탭 항목들 편집모드 닫기
    	    	for(int j=1; j<=9; j++) {
    				int textViewId = getResources().getIdentifier("textViewConcern" + j, "id", getPackageName());
    	    		if (textViewId <= 0) break;
    	    		int EditTextId = getResources().getIdentifier("editTextConcern" + j, "id", getPackageName());
    	    		if (EditTextId <= 0) break;
    				((EditText) findViewById(EditTextId)).setVisibility(View.GONE);
    				((TextView) findViewById(textViewId)).setText(((EditText) findViewById(EditTextId)).getText());
    				((TextView) findViewById(textViewId)).setVisibility(View.VISIBLE);
    			}
    	    	
//				Toast.makeText(act, "탭 바뀜 " + this, Toast.LENGTH_SHORT).show();
    	    	
    	    	// Facebook 탭 선택
    	    	if (tabId.equals("Tab4")) {
    	    		Log.d("ProfileActivity", "Facebook tab");
    	    		
    	        	TextView tv = (TextView)ProfileActivity.this.findViewById(R.id.textViewDefault2);
    	            String fbId = tv.getText().toString();
    	            
    	            Log.d("facebook", "fbId = " + fbId);
    	            
    	            if (fbId.equals("")) {
    	            	AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(ProfileActivity.this);
    	            	confirmBuilder.setMessage("기본정보에 페이스북 아이디를 입력해주세요.");
    	            	confirmBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
    	            		@Override
    	            		public void onClick(DialogInterface dialog, int which) {
    	            			dialog.dismiss();
    	            		}

    	            	});
    	            	confirmBuilder.show();
    	            } else {
    	            
    	            	mFacebook.authorize(ProfileActivity.this, 
    	            			new String[] {
    	            			"user_likes",
    	            			"user_about_me",
    	            			"friends_about_me",
    	            			"user_birthday",
    	            			"friends_birthday",
    	            			"user_education_history",
    	            			"friends_education_history", 
    	            			"email",
    	            			"user_hometown",
    	            			"friends_hometown",
    	            			"user_relationship_details",
    	            			"friends_relationship_details",
    	            			"user_location",
    	            			"friends_location",
    	            			"friends_activities",
    	            			"user_religion_politics",
    	            			"friends_religion_politics",
    	            			"user_likes",
    	            			"friends_likes",
    	            			"user_relationships",
    	            			"friends_relationships",
    	            			"user_website",
    	            			"friends_website",
    	            			"user_work_history",
    	            			"friends_work_history",
    	            			"user_activities",
    	            			"friends_activities",
    	            			"user_checkins",
    	            			"friends_checkins",
    	            			"user_events",
    	            			"friends_checkins",
    	            			"read_stream",
    	            			"read_friendlists",
    	            			"read_stream",
    	            			"user_interests",
    	            			"friends_interests",
    	            			"friends_education_history",
    	            			"friends_online_presence",
    	            			"friends_status"
    	            	}, 
    	            	new LoginDialogListener());
    	            }
    	    	}
			}
		});
        
        
        
        
        
        /***********************************************************************
		 * 
		 * 
		 * 사진 설정
		 * 
		 * 
		 ***********************************************************************/
        ((ImageView)findViewById(R.id.imageViewPerson)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("imageClick", v.toString());
				
				Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), SELECT_PICTURE);
				
			}
		});
        
        
        
        
        
        
		/***********************************************************************
		 * 
		 * 
		 * 항목 선택 시, 편집모드와 뷰모드 전환
		 * 
		 * 
		 ***********************************************************************/
        //
        // 0. 이름 항목
        //
        ((LinearLayout) findViewById(R.id.linearLayoutName)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(tabHost.getCurrentTab() == 0) {
					// 기본정보 탭 전체 편집모드 닫기
					for(int j=1; j<=Constant.PROFILE_DEFAULT_COUNT; j++) {
						int otherTxtID = getResources().getIdentifier("textViewDefault" + j, "id", getPackageName());
			    		if (otherTxtID <= 0) break;
			    		int otherEdtID = getResources().getIdentifier("editTextDefault" + j, "id", getPackageName());
			    		if (otherEdtID <= 0) break;
						((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
						((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
						((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
					}
					
					// 이름 항목 편집모드 열기
					((TextView) findViewById(R.id.textViewName)).setVisibility(View.GONE);
					((EditText) findViewById(R.id.editTextName)).setText(((TextView) findViewById(R.id.textViewName)).getText());
					((EditText) findViewById(R.id.editTextName)).setVisibility(View.VISIBLE);
					((EditText) findViewById(R.id.editTextName)).requestFocus();
				}
				else if(tabHost.getCurrentTab() == 1) {
					// 관심사 탭 항목들 편집모드 닫기 (1~9)
	    	    	for(int j=1; j<=9; j++) {
	    				int otherTxtID = getResources().getIdentifier("textViewConcern" + j, "id", getPackageName());
	    	    		if (otherTxtID <= 0) break;
	    	    		int otherEdtID = getResources().getIdentifier("editTextConcern" + j, "id", getPackageName());
	    	    		if (otherEdtID <= 0) break;
	    				((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
	    				((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
	    				((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
	    			}
				}
				
			}
		});


        //
        // 1. 기본정보 탭
        //
        for(int i=1; i<=Constant.PROFILE_DEFAULT_COUNT; i++) {
        	int layId = getResources().getIdentifier("linearLayoutDefault" + i, "id", getPackageName());
    		if (layId <= 0) break;
    		final int txtID = getResources().getIdentifier("textViewDefault" + i, "id", getPackageName());
    		if (txtID <= 0) break;
    		final int edtID = getResources().getIdentifier("editTextDefault" + i, "id", getPackageName());
    		if (edtID <= 0) break;
    		
	        ((LinearLayout) findViewById(layId)).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					// 가정 먼저 이름 편집모드 닫기
					((EditText) findViewById(R.id.editTextName)).setVisibility(View.GONE);
					((TextView) findViewById(R.id.textViewName)).setText(((EditText) findViewById(R.id.editTextName)).getText());
					((TextView) findViewById(R.id.textViewName)).setVisibility(View.VISIBLE);
					
					// 전체 항목 편집모드 닫기
					for(int j=1; j<=8; j++) {
						int otherTxtID = getResources().getIdentifier("textViewDefault" + j, "id", getPackageName());
			    		if (otherTxtID <= 0) break;
			    		int otherEdtID = getResources().getIdentifier("editTextDefault" + j, "id", getPackageName());
			    		if (otherEdtID <= 0) break;
						((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
						((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
						((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
					}
					
					// 현재 선택된 항목 편집모드 열기
					((TextView) findViewById(txtID)).setVisibility(View.GONE);
					((EditText) findViewById(edtID)).setText(((TextView) findViewById(txtID)).getText());
					((EditText) findViewById(edtID)).setVisibility(View.VISIBLE);
					((EditText) findViewById(edtID)).requestFocus();
				}
			});
        }


        //
        // 2. 관심사 탭 (1~9 항목)
        //
        for(int i=1; i<=9; i++) {
        	int layId = getResources().getIdentifier("linearLayoutConcern" + i, "id", getPackageName());
    		if (layId <= 0) break;
    		final int txtID = getResources().getIdentifier("textViewConcern" + i, "id", getPackageName());
    		if (txtID <= 0) break;
    		final int edtID = getResources().getIdentifier("editTextConcern" + i, "id", getPackageName());
    		if (edtID <= 0) break;
    		
	        ((LinearLayout) findViewById(layId)).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					// 가정 먼저 이름 편집모드 닫기
//					((EditText) findViewById(R.id.editTextName)).setVisibility(View.GONE);
//					((TextView) findViewById(R.id.textViewName)).setText(((EditText) findViewById(R.id.editTextName)).getText());
//					((TextView) findViewById(R.id.textViewName)).setVisibility(View.VISIBLE);
					
					// 전체 항목 편집모드 닫기
					for(int j=1; j<=9; j++) {
						int otherTxtID = getResources().getIdentifier("textViewConcern" + j, "id", getPackageName());
			    		if (otherTxtID <= 0) break;
			    		int otherEdtID = getResources().getIdentifier("editTextConcern" + j, "id", getPackageName());
			    		if (otherEdtID <= 0) break;
						((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
						((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
						((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
					}
					
					// 현재 선택된 항목 편집모드 열기
					((TextView) findViewById(txtID)).setVisibility(View.GONE);
					((EditText) findViewById(edtID)).setText(((TextView) findViewById(txtID)).getText());
					((EditText) findViewById(edtID)).setVisibility(View.VISIBLE);
					((EditText) findViewById(edtID)).requestFocus();
				}
			});
        }

        
        //
        // 3. 별점 탭
        //
        for(int i=1; i<=Constant.PROFILE_RATING_COUNT; i++) {
        	final int ratingBarId = getResources().getIdentifier("ratingBar" + i, "id", getPackageName());
    		if (ratingBarId <= 0) break;
    		final int textViewId = getResources().getIdentifier("textViewRating" + i, "id", getPackageName());
    		if (textViewId <= 0) break;
        	
	        ((RatingBar)findViewById(ratingBarId)).setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
				@Override
				public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
					((TextView)findViewById(textViewId)).setText(String.valueOf(rating));
										
					// Total 별점 계산
					for(int j=1; j<=Constant.PROFILE_RATING_COUNT; j++) {
						int ratingBarId = getResources().getIdentifier("ratingBar" + j, "id", getPackageName());
			    		if (ratingBarId <= 0) break;
			    		
			    		totalRating += ((RatingBar)findViewById(ratingBarId)).getRating();
					}
					if(totalRating > 0) {
						totalRating /= Constant.PROFILE_RATING_COUNT;
						totalRating *= 10.0;
						totalRating = (int)totalRating;
						totalRating /= 10.0;
					}
					
					// Total 별점 반영
					((RatingBar)findViewById(R.id.ratingBarTotal)).setRating(totalRating);
					((TextView)findViewById(R.id.textViewRatingTotal)).setText(String.valueOf(totalRating));
				}
			});
        }
        
        
        //
        // 4. 페이스북 정보 탭
        //
        
        
        ///////////////////// 코딩요망
        
        
        
        
        
        
        /***********************************************************************
    	 * 
    	 * 
    	 * 인탠트 전환 시, 항목 채워 넣기
    	 * 
    	 * 
    	 ***********************************************************************/
        Intent currentIntent = getIntent();
        if(currentIntent != null) {
        	
        	dataProfile = (DataProfile)currentIntent.getSerializableExtra("ObjectData");
        	
        	// 새로운 사람인 경우
        	if(dataProfile == null) {
            	
//            	Toast.makeText(act, "새로운 사람이라네", Toast.LENGTH_SHORT).show();
        		
            	((TextView)findViewById(R.id.textViewName)).setVisibility(View.GONE);
            	((EditText)findViewById(R.id.editTextName)).setVisibility(View.VISIBLE);
            	((EditText)findViewById(R.id.editTextName)).requestFocus();
            	
            }
            
            // 전화번호부에서 가져왔거나 기존사람인 경우
            else {
            	
//            	Toast.makeText(act, "새로운 사람이 아니라네", Toast.LENGTH_SHORT).show();
            	
            	// 사진과 이름
            	((TextView)findViewById(R.id.textViewName)).setText(dataProfile.getName());
            	((EditText)findViewById(R.id.editTextName)).setText(dataProfile.getName());

            	// 사진
            	m_picturePath = dataProfile.getPicturePath();
            	if (!m_picturePath.equals("")) {
            		Bitmap bMap = BitmapFactory.decodeFile(m_picturePath);
                    ImageView image = (ImageView) findViewById(R.id.imageViewPerson);
                    image.setImageBitmap(bMap);
            	}
            	
            	// 기본 정보
            	((TextView)findViewById(R.id.textViewDefault1)).setText(dataProfile.getMobileNo());
            	((TextView)findViewById(R.id.textViewDefault2)).setText(dataProfile.getFacebookId());
            	((TextView)findViewById(R.id.textViewDefault3)).setText(dataProfile.getEmail());
            	((TextView)findViewById(R.id.textViewDefault4)).setText(dataProfile.getHomeAddr());
            	((TextView)findViewById(R.id.textViewDefault5)).setText(dataProfile.getBirth());
            	((TextView)findViewById(R.id.textViewDefault6)).setText(dataProfile.getBloodType());
            	
            	((EditText)findViewById(R.id.editTextDefault1)).setText(dataProfile.getMobileNo());
            	((EditText)findViewById(R.id.editTextDefault2)).setText(dataProfile.getFacebookId());
            	((EditText)findViewById(R.id.editTextDefault3)).setText(dataProfile.getEmail());
            	((EditText)findViewById(R.id.editTextDefault4)).setText(dataProfile.getHomeAddr());
            	((EditText)findViewById(R.id.editTextDefault5)).setText(dataProfile.getBirth());
            	((EditText)findViewById(R.id.editTextDefault6)).setText(dataProfile.getBloodType());
            	
            	// 관심사
            	((TextView)findViewById(R.id.textViewConcern1)).setText(dataProfile.getFavorMusic());
            	((TextView)findViewById(R.id.textViewConcern2)).setText(dataProfile.getFavorMovie());
            	((TextView)findViewById(R.id.textViewConcern3)).setText(dataProfile.getFavorTv());
            	((TextView)findViewById(R.id.textViewConcern4)).setText(dataProfile.getFavorBook());
            	((TextView)findViewById(R.id.textViewConcern5)).setText(dataProfile.getFavorGame());
            	((TextView)findViewById(R.id.textViewConcern6)).setText(dataProfile.getFavorPeople());
            	((TextView)findViewById(R.id.textViewConcern7)).setText(dataProfile.getFavorSports());
            	((TextView)findViewById(R.id.textViewConcern8)).setText(dataProfile.getFavorHobby());
            	((TextView)findViewById(R.id.textViewConcern9)).setText(dataProfile.getFavorDislike());
            	
            	((EditText)findViewById(R.id.editTextConcern1)).setText(dataProfile.getFavorMusic());
            	((EditText)findViewById(R.id.editTextConcern2)).setText(dataProfile.getFavorMovie());
            	((EditText)findViewById(R.id.editTextConcern3)).setText(dataProfile.getFavorTv());
            	((EditText)findViewById(R.id.editTextConcern4)).setText(dataProfile.getFavorBook());
            	((EditText)findViewById(R.id.editTextConcern5)).setText(dataProfile.getFavorGame());
            	((EditText)findViewById(R.id.editTextConcern6)).setText(dataProfile.getFavorPeople());
            	((EditText)findViewById(R.id.editTextConcern7)).setText(dataProfile.getFavorSports());
            	((EditText)findViewById(R.id.editTextConcern8)).setText(dataProfile.getFavorHobby());
            	((EditText)findViewById(R.id.editTextConcern9)).setText(dataProfile.getFavorDislike());
            	
            	// 별점
            	if (!dataProfile.getRateAppearance().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar1)).setRating(Float.parseFloat(dataProfile.getRateAppearance()));
            	}

            	if (!dataProfile.getRateBodyShape().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar2)).setRating(Float.parseFloat(dataProfile.getRateBodyShape()));
            	}

            	if (!dataProfile.getRateMoney().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar3)).setRating(Float.parseFloat(dataProfile.getRateMoney()));
            	}

            	if (!dataProfile.getRateCharacter().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar4)).setRating(Float.parseFloat(dataProfile.getRateCharacter()));
            	}

            	if (!dataProfile.getRateAcademic().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar5)).setRating(Float.parseFloat(dataProfile.getRateAcademic()));
            	}

            	if (!dataProfile.getRateHousehold().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBar6)).setRating(Float.parseFloat(dataProfile.getRateHousehold()));
            	}

            	if (!dataProfile.getRateTotal().equals("")) {
            		((RatingBar)findViewById(R.id.ratingBarTotal)).setRating(Float.parseFloat(dataProfile.getRateTotal()));
            	}
            	
            	((TextView)findViewById(R.id.textViewRating1)).setText(dataProfile.getRateAppearance());
            	((TextView)findViewById(R.id.textViewRating2)).setText(dataProfile.getRateBodyShape());
            	((TextView)findViewById(R.id.textViewRating3)).setText(dataProfile.getRateMoney());
            	((TextView)findViewById(R.id.textViewRating4)).setText(dataProfile.getRateCharacter());
            	((TextView)findViewById(R.id.textViewRating5)).setText(dataProfile.getRateAcademic());
            	((TextView)findViewById(R.id.textViewRating6)).setText(dataProfile.getRateHousehold());
            	((TextView)findViewById(R.id.textViewRatingTotal)).setText(dataProfile.getRateTotal());
            	
            }
        }
    }
    
    
    
    
    
    /***********************************************************************
	 * 
	 * 
	 * 함수 : 모든 항목 뷰모드로 전환하기
	 * 
	 * 
	 ***********************************************************************/
    private void requestViewModeAll() {
    	
    	// 이름 항목 편집모드 닫기
    	((EditText) findViewById(R.id.editTextName)).setVisibility(View.GONE);
		((TextView) findViewById(R.id.textViewName)).setText(((EditText) findViewById(R.id.editTextName)).getText());
		((TextView) findViewById(R.id.textViewName)).setVisibility(View.VISIBLE);
    	
    	// 기본정보 탭 항목들 편집모드 닫기
    	for(int j=1; j<=Constant.PROFILE_DEFAULT_COUNT; j++) {
			int otherTxtID = getResources().getIdentifier("textViewDefault" + j, "id", getPackageName());
    		if (otherTxtID <= 0) break;
    		int otherEdtID = getResources().getIdentifier("editTextDefault" + j, "id", getPackageName());
    		if (otherEdtID <= 0) break;
			((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
			((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
			((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
		}
    	
    	// 관심사 탭 항목들 편집모드 닫기
    	for(int j=1; j<=9; j++) {
			int otherTxtID = getResources().getIdentifier("textViewConcern" + j, "id", getPackageName());
    		if (otherTxtID <= 0) break;
    		int otherEdtID = getResources().getIdentifier("editTextConcern" + j, "id", getPackageName());
    		if (otherEdtID <= 0) break;
			((EditText) findViewById(otherEdtID)).setVisibility(View.GONE);
			((TextView) findViewById(otherTxtID)).setText(((EditText) findViewById(otherEdtID)).getText());
			((TextView) findViewById(otherTxtID)).setVisibility(View.VISIBLE);
		}
    }
    
    
    
    
    
    /***********************************************************************
	 * 
	 * 
	 * Back-Key 이벤트
	 * 
	 * 
	 ***********************************************************************/
    @Override
    public void onBackPressed() {
    	
    	// 모든 항목들을 뷰모드로 전환
    	requestViewModeAll();
		
    	
		// 이름 입력 확인
    	if(((TextView)findViewById(R.id.textViewName)).getText().toString().compareTo("") == 0) {
    		
    		new AlertDialog.Builder(ProfileActivity.this)
    		.setTitle("경고")
    		.setMessage("이름이 입력되지 않으면 저장할 수 없습니다. 메인화면으로 가시겠습니까?")
    		.setPositiveButton("예", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					// 예를 누른 경우 - 메인화면 가기
					onBackPressed();
				}
			}).setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					// 아니오를 누른 경우 - 이름에 다시 포커스
	        		((TextView) findViewById(R.id.textViewName)).setVisibility(View.GONE);
					((EditText) findViewById(R.id.editTextName)).setText(((TextView) findViewById(R.id.textViewName)).getText());
					((EditText) findViewById(R.id.editTextName)).setVisibility(View.VISIBLE);
					((EditText) findViewById(R.id.editTextName)).requestFocus();
				}
			}).show();
    	}
    	
    	// 휴대폰번호 입력 확인
    	else if(((TextView)findViewById(R.id.textViewDefault1)).getText().toString().compareTo("") == 0) {
    		
    		new AlertDialog.Builder(ProfileActivity.this)
    		.setTitle("경고")
    		.setMessage("휴대폰번호가 입력되지 않으면 저장할 수 없습니다. 메인화면으로 가시겠습니까?")
    		.setPositiveButton("예", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					// 예를 누른 경우 - 메인화면 가기
					onBackPressed();
				}
			}).setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					// 아니오를 누른 경우 - 휴대폰번호에 다시 포커스
	        		((TextView) findViewById(R.id.textViewDefault1)).setVisibility(View.GONE);
					((EditText) findViewById(R.id.editTextDefault1)).setVisibility(View.VISIBLE);
					((EditText) findViewById(R.id.editTextDefault1)).requestFocus();
				}
			}).show();
    	}
		
    	
		// DB 저장
    	else {
    		
    		if(dataProfile == null) dataProfile = new DataProfile();
    		
    		// 사진과 이름
    		dataProfile.setName(((TextView)findViewById(R.id.textViewName)).getText().toString());
    		dataProfile.setPicturePath(m_picturePath);
    		
    		// 기본정보
    		dataProfile.setMobileNo(((TextView)findViewById(R.id.textViewDefault1)).getText().toString());
    		dataProfile.setFacebookId(((TextView)findViewById(R.id.textViewDefault2)).getText().toString());
    		dataProfile.setEmail(((TextView)findViewById(R.id.textViewDefault3)).getText().toString());
    		dataProfile.setHomeAddr(((TextView)findViewById(R.id.textViewDefault4)).getText().toString());
    		dataProfile.setBirth(((TextView)findViewById(R.id.textViewDefault5)).getText().toString());
    		dataProfile.setBloodType(((TextView)findViewById(R.id.textViewDefault6)).getText().toString());
    		
    		// 관심사
    		dataProfile.setFavorMusic(((TextView)findViewById(R.id.textViewConcern1)).getText().toString());
    		dataProfile.setFavorMovie(((TextView)findViewById(R.id.textViewConcern2)).getText().toString());
    		dataProfile.setFavorTv(((TextView)findViewById(R.id.textViewConcern3)).getText().toString());
    		dataProfile.setFavorBook(((TextView)findViewById(R.id.textViewConcern4)).getText().toString());
    		dataProfile.setFavorGame(((TextView)findViewById(R.id.textViewConcern5)).getText().toString());
    		dataProfile.setFavorPeople(((TextView)findViewById(R.id.textViewConcern6)).getText().toString());
    		dataProfile.setFavorSports(((TextView)findViewById(R.id.textViewConcern7)).getText().toString());
    		dataProfile.setFavorHobby(((TextView)findViewById(R.id.textViewConcern8)).getText().toString());
    		dataProfile.setFavorDislike(((TextView)findViewById(R.id.textViewConcern9)).getText().toString());
    		
    		// 별점
    		dataProfile.setRateAppearance(((TextView)findViewById(R.id.textViewRating1)).getText().toString());
    		dataProfile.setRateBodyShape(((TextView)findViewById(R.id.textViewRating2)).getText().toString());
    		dataProfile.setRateMoney(((TextView)findViewById(R.id.textViewRating3)).getText().toString());
    		dataProfile.setRateCharacter(((TextView)findViewById(R.id.textViewRating4)).getText().toString());
    		dataProfile.setRateAcademic(((TextView)findViewById(R.id.textViewRating5)).getText().toString());
    		dataProfile.setRateHousehold(((TextView)findViewById(R.id.textViewRating6)).getText().toString());
    		dataProfile.setRateTotal(((TextView)findViewById(R.id.textViewRatingTotal)).getText().toString());
    		
    		// DB 저장
    		DbManager dbm = DbManager.getInstance(ProfileActivity.this);
    		dbm.saveProfile(dataProfile);
    		
    		// 메인화면 가기
    		super.onBackPressed();
    		
    	}
    }
    
    /***********************************************************************
	 * 
	 * 
	 * 액티비티 호출 결과 처리
	 * 
	 * 
	 ***********************************************************************/
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                m_picturePath = getPath(selectedImageUri);
                Log.d("ProfileActivity", "picture path = " + m_picturePath);
                Bitmap bMap = BitmapFactory.decodeFile(m_picturePath);
                ImageView image = (ImageView) findViewById(R.id.imageViewPerson);
                image.setImageBitmap(bMap);
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
        		
    
    
    /***********************************************************************
	 * 
	 * 
	 * 화면 터치 이벤트
	 * 
	 * 
	 ***********************************************************************/
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	
//    	Toast.makeText(act, "any 터치" + this, Toast.LENGTH_SHORT).show();
    	
    	// 모든 항목들을 뷰모드로 전환
    	requestViewModeAll();
		
    	return super.onTouchEvent(event);
    }
    
    
    
    
    
    
    /***********************************************************************
	 * 
	 * 
	 * 옵션 메뉴
	 * 
	 * 
	 ***********************************************************************/
 	@Override
 	public boolean onPrepareOptionsMenu(Menu menu) {
 		new ProfileOptionMenu(this).initMenu(menu);	// 메뉴 시작시 작업이 필요할 경우
 		return super.onPrepareOptionsMenu(menu);
 	}

 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		MenuInflater inflater = getMenuInflater();
 		inflater.inflate(R.menu.profile_option_menu, menu);
 		return true;
 	}

 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 		boolean tmp = new ProfileOptionMenu(this).initSelected(item);
 		if (tmp)
 			return tmp;
 		else
 			return super.onOptionsItemSelected(item);
 	}
 	
 	
 	
 	private class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {
        	Log.d("Facebook", "You have logged in! ");
        	SessionStore.save(mFacebook, ProfileActivity.this);
        	
        	
        	TextView tv = (TextView)ProfileActivity.this.findViewById(R.id.textViewDefault2);
            String fbId = tv.getText().toString();
            
            Log.d("facebook", "fbId = " + fbId);
            
        	mAsyncRunner.request(fbId, new ProfileRequestListener());
        }

        public void onAuthFail(String error) {
        	Log.d("Facebook", "Login Failed: " + error);
        }
    }
 	
 	private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
 	
 	public class ProfileRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook", "Response: " + response.toString());
                
                JSONObject json = Util.parseJson(response);
                String strFacebook = "";
                String strTmp = null;
                JSONObject tmpObj = null;
                
                try {
                	strTmp = json.getString("id");
                	strFacebook += "* ID : " + strTmp + "\n";
                } catch (JSONException e) {
                }

                try {
                	strTmp = json.getString("name");
                	strFacebook += "* 이름 : " + strTmp + "\n";
                } catch (JSONException e) {
                }
                
                try {
                	tmpObj = json.getJSONObject("hometown");
                	strTmp = tmpObj.getString("name");
                	strFacebook += "* 고향 : " + strTmp + "\n";
                } catch (JSONException e) {
                }
                
                try {
                	tmpObj = json.getJSONObject("location");
                	strTmp = tmpObj.getString("name");
                	strFacebook += "* 위치 : " + strTmp + "\n";
                } catch (JSONException e) {
                }
                
                // 성별
                try {
                	strTmp = json.getString("gender");
                	strFacebook += "* 성별 : " + strTmp + "\n";
                } catch (JSONException e) {
                }
                
                // 직장
                JSONArray arrWorks = new JSONArray();
                
                try {
                	arrWorks = json.getJSONArray("work");
                	strFacebook += "* 직장 : \n";
                } catch (JSONException e) {
            	}

                for (int i = 0; i < arrWorks.length(); i++) {
                	tmpObj = arrWorks.getJSONObject(i).getJSONObject("employer");
                	strTmp = tmpObj.getString("name");
                	strFacebook += "   - " + strTmp;
                
                	try {
                		tmpObj = arrWorks.getJSONObject(i).getJSONObject("position");
                		strTmp = tmpObj.getString("name");
                		strFacebook += "/" + strTmp;
                	} catch (JSONException e) {
                	}
                
                	String strStartDate = null;
                	try {
                		strStartDate = arrWorks.getJSONObject(i).getString("start_date");
                	} catch (JSONException e) {
                	}

                	String strEndDate = null;
                	try {
                		strEndDate = arrWorks.getJSONObject(i).getString("end_date");
                	} catch (JSONException e) {
                	}

                	if (strStartDate != null || strEndDate != null) {
                		if (strStartDate != null) {
                			strFacebook += "/" + strStartDate + "~";
                		} else {
                			strFacebook += "/" + "~";
                		}
                		
                		if (strEndDate != null) {
                			strFacebook += strEndDate;
                		}
                	}
                	
                	strFacebook += "\n";
                }
                
                // 학교
                JSONArray arrEdu = new JSONArray();
                
                try {
                	arrEdu = json.getJSONArray("education");
                	strFacebook += "* 학교 : \n";
                } catch (JSONException e) {
            	}

                for (int i = 0; i < arrEdu.length(); i++) {
                	tmpObj = arrEdu.getJSONObject(i).getJSONObject("school");
                	strTmp = tmpObj.getString("name");
                	strFacebook += "   - " + strTmp;
                
                	try {
                		tmpObj = arrEdu.getJSONObject(i).getJSONObject("year");
                		strTmp = tmpObj.getString("name");
                		strFacebook += "/" + strTmp + "년 졸업";
                	} catch (JSONException e) {
                	}
                	
                	try {
                		tmpObj = arrEdu.getJSONObject(i).getJSONObject("degree");
                		strTmp = tmpObj.getString("name");
                		strFacebook += "/" + strTmp;
                	} catch (JSONException e) {
                	}
                	
                	try {
                		JSONArray arrCon = arrEdu.getJSONObject(i).getJSONArray("concentration");
                		
                		for (int j = 0; j < arrCon.length(); j++) {
                			strTmp = arrCon.getJSONObject(j).getString("name");
                			strFacebook += "/" + strTmp;
                		}
                	} catch (JSONException e) {
                	}
                	
                	try {
                		strTmp = arrEdu.getJSONObject(i).getString("type");
                		strFacebook += "/" + strTmp;
                	} catch (JSONException e) {
                	}
                
                	strFacebook += "\n";
                }
                
                // 좋아하는 인용구
                try {
                	strTmp = json.getString("quotes");
                	strFacebook += "* 좋아하는 인용구 : \n" + strTmp + "\n";
                } catch (JSONException e) {
                }
                
                // 감명을 준 사람
                JSONArray arrIns = new JSONArray();
                
                try {
                	arrIns = json.getJSONArray("inspirational_people");
                	strFacebook += "* 감명을 준 사람 : \n";
                } catch (JSONException e) {
            	}

                for (int i = 0; i < arrIns.length(); i++) {
                	strTmp = arrIns.getJSONObject(i).getString("name");
                	strFacebook += "   - " + strTmp;
                	strFacebook += "\n";
                }
                
                // 최종 업데이트 시간
                strTmp = json.getString("updated_time");

                if (strTmp != null) {
                	strFacebook += "* 최종업데이트 : " + strTmp + "\n";
                }
                

                final String strResult = strFacebook;

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                ProfileActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                    	TextView tv = (TextView)ProfileActivity.this.findViewById(R.id.tv_facebook);
                        tv.setText(strResult);
                        
                        // likes 요청
                        tv = (TextView)ProfileActivity.this.findViewById(R.id.textViewDefault2);
                        String fbId = tv.getText().toString();
                        mAsyncRunner.request(fbId + "/likes", new LikesRequestListener());
                    }
                }); 
                
            } catch (JSONException e) {
                Log.w("Facebook", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook", "Facebook Error: " + e.getMessage());
                final FacebookError err = e;
                
                /*
                ProfileActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        
                        AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(ProfileActivity.this);
                    	confirmBuilder.setMessage("Facebook Error: " + err.getMessage());
                    	confirmBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    		@Override
                    		public void onClick(DialogInterface dialog, int which) {
                    			dialog.dismiss();
                    		}

                    	});
                    	confirmBuilder.show();
                    }
                }); 
                */
                

            }
        }
    }
 	
 	public class LikesRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook", "Response: " + response.toString());
                
                JSONObject json = Util.parseJson(response);
                String strFacebook = "";
                String strTmp = null;
                JSONObject tmpObj = null;
                
                // Likes
                JSONArray arrLikes = new JSONArray();
                
                try {
                	arrLikes = json.getJSONArray("data");
                	strFacebook += "* 좋아하는 것 : \n";
                } catch (JSONException e) {
            	}

                for (int i = 0; i < arrLikes.length(); i++) {
                	strTmp = arrLikes.getJSONObject(i).getString("name");
                	strFacebook += "   - " + strTmp;
                
                	try {
                    	strTmp = arrLikes.getJSONObject(i).getString("category");
                    	strFacebook += "/" + strTmp;
                	} catch (JSONException e) {
                	}
                	
                	strFacebook += "\n";
                }

                final String strResult = strFacebook;

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                ProfileActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                    	TextView tv = (TextView)ProfileActivity.this.findViewById(R.id.tv_facebook);
                        tv.setText(tv.getText() + strResult);
                        
                    }
                }); 
                
            } catch (JSONException e) {
                Log.w("Facebook", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook", "Facebook Error: " + e.getMessage());
            }
        }
    }


}